<!--对话框：上传excel导入-->
<template>
  <div>
    <a-dropdown-button @click="open">
      导入用户
      <template #content>
        <a-doption @click="downloadTemplate">
          <template #icon> <icon-download /> </template>
          下载模板
        </a-doption>
      </template>
    </a-dropdown-button>
    <a-modal :visible="visible" title="excel上传" @cancel="close" @ok="submit">
      <a-upload
        :file-list="fileList"
        draggable
        accept=".xml,.xlsx"
        :auto-upload="false"
        @change="onFileChange"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts" name="ImportUserModal">
  import { ref } from 'vue';
  import { FileItem, Message } from '@arco-design/web-vue';
  import { importUserRecord, downloadUserTemplate } from '@/api/system/user';

  const visible = ref(false);
  const emits = defineEmits(['afterSubmit']);
  const fileList = ref<FileItem[]>([]);
  const onFileChange = (files: FileItem[], file: FileItem) => {
    file.status = 'done';
    fileList.value = [...files];
  };

  const downloadTemplate = async () => {
    try {
      const res = (await downloadUserTemplate()) as unknown as Blob;
      const elink = document.createElement('a');
      elink.download = '批量导入用户模板.xlsx';
      elink.style.display = 'none';
      const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      document.body.removeChild(elink);
    } finally {
      // empty
    }
  };
  const upload = async () => {
    const formData = new FormData();
    formData.append('file', fileList.value[0].file as File);
    try {
      await importUserRecord(formData);
      Message.success('导入成功');
    } finally {
      emits('afterSubmit');
    }
  };
  const open = () => {
    visible.value = true;
  };
  const close = () => {
    fileList.value = [];
    visible.value = false;
  };
  const submit = () => {
    upload();
    close();
  };
</script>
